$(function () {
    var couponCache = {};
    /**
     * 初始化红包列表
     */
    var initCouponTable = function () {
        chinese.sInfo = "共 _TOTAL_ 条";
        chinese.sInfoEmpty = "";
        var table = $('#couponList').DataTable({
            //"processing": true,
            //"serverSide": true,
            "sort": false,
            "search": false,
            "ajax": {
                "url": "coupon/listCouponPack",
//                "data": function (d) {
//                    //d.fundStatus = fundStatus.val();
//                },
                "type": "GET"
            },
            "aoColumnDefs": [{
                    "targets": 0,
                    "className": 'details-control',
                    "mRender": function (data, type, row) {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                }, {
                    "targets": 1,
                    "mRender": function (data, type, row) {
                        return row.name;
                    }
                }, {
                    "targets": 2,
                    "mRender": function (data, type, row) {
                        return sysRewardEventType[row.eventType];
                    }
                }, {
                    "targets": 3,
                    "mRender": function (data, type, row) {
                        return row.bonus;
                    }
                }, {
                    "targets": 4,
                    "mRender": function (data, type, row) {
                        return $.number(row.minInvestAmount);
                    }
                }, {
                    "targets": 5,
                    "visible": false,
                    "mRender": function (data, type, row) {
                        return row.creator.realm;
                    }
                }, {
                    "targets": 6,
                    "mRender": function (data, type, row) {
                        return $.format.date(row.availableTime, "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 7,
                    "mRender": function (data, type, row) {
                        return $.format.date(row.expiredTime, "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 8,
                    "mRender": function (data, type, row) {
                        return row.expiredDays + '天';
                    }
                }, {
                    "targets": 9,
                    "mRender": function (data, type, row) {
                        var operations = $("#operationHTML").html().replace(/#id/g, row.id);
                        return operations;
                    }
                }],
            "order": [3, 'desc'],
            "oLanguage": chinese,
            "iDisplayLength": 10,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lip>',
//             "sDom": '<"dt-panelmenu clearfix"l<"pull-right"T>r>t<"dt-panelfooter clearfix"ip>',
//            "oTableTools": {
//                "aButtons": [{
//                        "sExtends": "xls",
//                        "sButtonText": "导出为Excel"
//                    }
//                ],
//                "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
//            }
            "initComplete": function (settings, json) {
                cacheCouponPack(json);
            },
            "rowCallback": function (row, data, index) {
                $(row).data("id", data.id).addClass("cursor-pointer text-muted");
            }
        });

        function cacheCouponPack(json) {
            if (json.recordsTotal > 0) {
                // 缓存部门列表
                $.map(json.data, function (cp) {
                    couponCache[cp.id] = cp;
                });
            }
        }
        /**
         * 详情展开/关闭
         */
        $('#couponList tbody').on('click', 'td.details-control', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // 关闭详情
                $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // 展开详情
                $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
                var id = row.data().id, cp = couponCache[id], detail = '<p class="text-center mt20 mb20">尚无满足条件的用户</p>';

                if (cp.placements === undefined) {
                    var members = [];
                    cp.placements = members;
                    cp.registerDate = function () {
                        if (cp.eventType === 'USER_REGISTER' || cp.eventType === 'POINT_EXCHANGE_COUPON') {
                            return $.format.date(this.user.registerTime, "yyyy/MM/dd HH:mm");
                        } else if(cp.eventType === 'USER_INVEST'){
                            return $.format.date(this.user.registerTime, "yyyy/MM/dd HH:mm");
                        }
                        else if(cp.eventType === 'USER_INVEST_CYCLE'){
                            return $.format.date(this.user.registerTime, "yyyy/MM/dd HH:mm");
                        }
                        else if(cp.eventType === 'USER_RECOMMEND_CAPITAL'){
                            return $.format.date(this.user.registerTime, "yyyy/MM/dd HH:mm");
                        }
                        else{
                            return $.format.date(this.friend.registerTime, "yyyy/MM/dd HH:mm");
                        }
                    };
                    cp.account = function () {
                        return this.hasAccount ? "已开户" : "未开户";
                    };
                    cp.status = function () {
                        var s = sysRewardStatus[this.ticket.status];
                        if (this.ticket.status === 'PAYED') {
                            return '<i class="fa fa-lock text-alert mr5"></i>' + s;
                        } else if (this.ticket.status === 'ALLOCATED') {
                            return '<i class="fa fa-certificate text-warning mr5"></i>' + s;
                        } else if (this.ticket.status === 'QUALIFIED') {
                            return '<i class="fa fa-check-circle text-success mr5"></i>' + s;
                        } else if (this.ticket.status === 'EXPIRED') {
                            return '<i class="fa fa-clock-o text-danger mr5"></i>' + s;
                        }
                        return s;
                    };
                    cp.active = function () {
                        return this.ticket.status === 'QUALIFIED' ? true : false;
                    };
                    cp.cancel = function () {
                        if (this.ticket.status === 'ALLOCATED' || this.ticket.status === 'QUALIFIED') {
                            return true;
                        }
                        return false;
                    };
                    $.get("coupon/listTicketByPack/" + id, function (res) {
                        if (res.recordsTotal > 0) {
                            for (var i = 0; i < res.recordsTotal; i++) {
                                var ticket = res.data[i];
                                members.push(ticket);
                            }
                            if (cp.eventType === 'USER_REGISTER') {
                                detail = sys.render("#couponPlacementTemplate", cp);
                            }
                            else if (cp.eventType === 'POINT_EXCHANGE_COUPON')
                            {
                                detail = sys.render("#exchangeTicketTemplate", cp); 
                            }else if(cp.eventType === 'USER_INVEST_CYCLE'){
                                detail = sys.render("#userInvestCycleTemplate", cp);
                            }
                            else if(cp.eventType === 'USER_RECOMMEND_CAPITAL'){
                                detail = sys.render("#userInvestCycleTemplate", cp);
                            }
                            else{
                                detail = sys.render("#refereeCouponTemplate", cp);
                            }
                        }
                        row.child(detail).show();
                        tr.addClass('shown');
                    }).fail(function () {
                        alert("网络通信错误");
                    });
                } else {
                    if (cp.placements.length > 0) {
                        if (cp.eventType === 'USER_REGISTER') {
                            detail = sys.render("#couponPlacementTemplate", cp);
                        }else if(cp.eventType === 'USER_INVEST'){
                            detail = sys.render("#investCouponTemplate", cp);
                        }else{
                            detail = sys.render("#refereeCouponTemplate", cp);
                        }
                    }
                    row.child(detail).show();
                    tr.addClass('shown');
                }
            }
        });

        /**
         * 红包打款
         */
        $('#couponList tbody').on('click', '.pay-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var pid = $(this).data("pid"), tid = $(this).data("tid"), uid = $(this).data("uid"), amount = $(this).data("amount"), btn = $(this);
            sys.confirm("确定打款？", function (btn) {
                var $btn = $(btn);
                sys.btnSpin($btn);
                sys.processModal();
                var data = {
                    ticketId: tid,
                    userId: uid,
                    amount: amount,
                    description: couponCache[pid].name + '_' + amount + '元_兑现'
                };
                $.post("coupon/payCouponTicket", data, function (res) {
                    if (res.success) {
                        var st = document.querySelector( '[data-st="'+tid+'"]' ) ;
                        var cz = document.querySelector( '[data-cz="'+tid+'"]' ) ;
                        $(st).html('<i class="fa fa-lock text-alert mr5"></i>已打款');
                        $(cz).html("");
                        alert("打款成功");
                        //sys.btnStop($btn);
                        sys.closeModal();
                        //location.reload();
                    } else {
                        alert("打款失败："+res.message);
                        sys.btnStop($btn);
                        sys.closeModal();
                    }
                }).fail(function () {
                    alert("网络通信错误");
                    sys.btnStop($btn);
                    sys.closeModal();
                });
            });
        });

        /**
         * 红包作废
         */
        $('#couponList tbody').on('click', '.reject-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tid = $(this).data("tid"), btn = $(this);
            sys.confirm("确定作废该红包？", function () {
                sys.processModal();
                $.get("coupon/cancelTicket/" + tid, function (res) {
                    if (res.success) {
                        alert("红包已作废");
                        location.reload();
                    } else {
                        alert("红包作废失败");
                        sys.closeModal();
                    }
                }).fail(function () {
                    alert("网络通信错误");
                    sys.closeModal();
                });
            });
        });
    };

    initCouponTable();
});
